package com.example.chatroom.service.impl;

import com.example.chatroom.entity.Room;
import com.example.chatroom.entity.User;
import com.example.chatroom.service.ChatService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author :ld
 * @date :2021/7/13
 */
@Service
public class ChatRoomServiceImpl implements ChatService {
    private static ConcurrentHashMap<String, Room> roomMap = new ConcurrentHashMap<String, Room>();
    private static ConcurrentHashMap<String, User> userMap = new ConcurrentHashMap<String, User>();

    @Override
    public String jionRoom(String roomId, String userId) {
        if (roomId==null || userId==null){
            return "房间名或用户名不能为空";
        }
        Room room = roomMap.get(roomId);
        User user = userMap.get(userId);
        if (room==null){
            return "房间名不存在";
        }
        if (user==null){
            return "用户名不存在";
        }
        List<User> users = room.getUsers();
        if (users==null){
            users = new ArrayList<>();
        }
        String res = Arrays.toString(users.toArray());
        if (users.contains(user)){
            return "用户已经在房间中，无法操作";
        }
        users.add(user);
        room.setUsers(users);
        if (users !=null && users.size()>0){
            return res;
        }
        return null;
    }

    @Override
    public String leaveRoom(String roomId, String userId) {
        if (roomId==null || userId==null){
            return "房间名或用户名不能为空";
        }
        Room room = roomMap.get(roomId);
        User user = userMap.get(userId);
        if (room==null){
            return "房间名不存在";
        }
        if (user==null){
            return "用户名不存在";
        }
        List<User> users = room.getUsers();
        if (users==null){
            users = new ArrayList<>();
        }
        if (!users.contains(user)){
            return "用户不在房间中，无法操作";
        }
        users.remove(user);
        room.setUsers(users);
        if (users !=null && users.size()>0){
            return Arrays.toString(users.toArray());
        }
        return null;
    }

    @Override
    public String createRoom(String roomName) {
        if (roomName==null){
            return "房间名不能为空";
        }
        Room room = roomMap.get(roomName);
        if (room == null){
            roomMap.put(roomName,new Room(roomName));
            return "房间["+roomName+"]，创建成功";
        }else {
            return "该房间已存在，无法创建";
        }
    }

    @Override
    public String createUser(String userName) {
        if (userName==null){
            return "用户名不能为空";
        }
        User user = userMap.get(userName);
        if (user == null){
            userMap.put(userName,new User(userName));
            return "用户["+userName+"]，创建成功";
        }else {
            return "该用户已存在，无法创建";
        }
    }
}
